#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <unistd.h>
#include "Task.hpp"

using namespace std;

const int defaultnum = 5;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

template <class T>
class ThreadPool
{
public:
    string GetThreadname(pthread_t tid)
    {
        for (auto &v : _vthread)
        {
            if (v.tid == tid)
            {
                return v.name;
            }
        }
    }

    static void *RunThread(void *args)
    {
        ThreadPool<T> *th = static_cast<ThreadPool<T> *>(args);

        string name = th->GetThreadname(pthread_self());

        while (1)
        {
            usleep(1000);
            Task data = th->pop();
            data.run();
            // cout << name << " 处理了一个任务" << data.GetResult() << endl;
        }
    }

public:
    void start()
    {
        for (int i = 0; i < _vthread.size(); i++)
        {
            _vthread[i].name = "thread" + to_string(i + 1);
            pthread_create(&(_vthread[i].tid), nullptr, RunThread, this);
        }
    }

    void push(const T &data)
    {
        pthread_mutex_lock(&_mutex);
        _q.push(data);
        pthread_mutex_unlock(&_mutex);

        pthread_cond_signal(&_cond);
    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_q.empty())
        {
            pthread_cond_wait(&_cond, &_mutex);
        }

        T data = _q.front();
        _q.pop();
        pthread_mutex_unlock(&_mutex);

        return data;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    // 懒汉模式
    static ThreadPool<T> *GetInstance()
    {
        if (tp == nullptr)
        {
            pthread_mutex_lock(&mutex);
            if (tp == nullptr)
            {
                tp = new ThreadPool();
            }
            pthread_mutex_unlock(&mutex);
        }

        return tp;
    }

private:
    ThreadPool(int size = defaultnum)
        : _vthread(size)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ThreadPool(const ThreadPool<T> &) = delete;
    ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

private:
    vector<ThreadInfo> _vthread;
    queue<T> _q;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *tp;
    static pthread_mutex_t mutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::mutex = PTHREAD_MUTEX_INITIALIZER;